package com.ysg.widget.pic.watermark;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Environment;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;

import com.ysg.R;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 水印图片工具类
 * 1.图片转bitmap
 * 2.通过Canvas，Paint对bitmap绘制水印
 * 3.保存bitmap图片
 */
public class WatermarkUtil {

    public interface OnWaterMaskListener{
        void onGetWaterMaskList(List<String> waterMaskList);
    }
    private static final String TAG = "WaterMaskUtil";
    public static final String DIR = Environment.getExternalStorageDirectory() + "/images/water/";
    /**
     * 图片上绘制文字
     */
    private float offsetLeftX = 50;
    private float offsetRightImageX = 0;
    private float offsetRightTextX = 0;
    private int lineHeight = 58;
    private float sumHeight = 300;
    private float backgroundHeight = 380;
    private float picHeight = 0;
    private float picWidth = 0;
    private float offsetRightY = 35;

    private float smallFontSize = 40;
    private float bigFontSize = 100;
    private int imageSize = 42;
    private float logoBottomOffset;
    private float logoRightOffset;
    private float logoHeight =  40;
    private float logoWidth = 95;

    private static WatermarkUtil instance = null;
    public static WatermarkUtil getInstance() {
        if (instance == null) {
            instance = new WatermarkUtil();
        }
        return instance;
    }

    public void build(Context context, List<String> images, WatermarkEntity waterMaskBean, OnWaterMaskListener listener){
        List<String> waterMaskList = new ArrayList<>();
        for (String path: images) {
            String waterMaskFilePath = getWaterMask(context, path, waterMaskBean);
            waterMaskList.add(waterMaskFilePath);
        }
        if (listener != null){
            listener.onGetWaterMaskList(waterMaskList);
        }
    }

    /**
     * 获取水印图片
     */
    public String getWaterMask(Context context, String originFilePath, WatermarkEntity waterMaskBean){
        //TODO 如果图片太大需要压缩,特别是拍照
        Bitmap bitmap = convertBitmap(context, originFilePath);
        bitmap = drawBitmap(context, waterMaskBean, bitmap);
        return saveWaterMask(context, bitmap);
    }

    /**
     * 图片文件转Bitmap
     */
    private Bitmap convertBitmap(Context context, String originFileName){
        long now = System.currentTimeMillis();
        Log.e("convertBitmap", ""+now);
        File file = new File(originFileName);
        if (file == null){
            Log.e(TAG, "水印图片文件不存在");
            return null;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        long now1 = System.currentTimeMillis();
        Log.e("convertBitmap", ""+now1);
        Log.e("convertBitmap", ""+(now1-now));
        return bitmap;
    }

    /**
     * 绘制水印后的bitmap
     */
    public Bitmap drawBitmap(Context context, WatermarkEntity waterMaskBean, Bitmap bitmap) {
        long now = System.currentTimeMillis();
        Log.e("drawBitmap", ""+now);
        bitmap = drawBackground(bitmap);
        bitmap = drawText(context, bitmap, waterMaskBean);
        long now1 = System.currentTimeMillis();
        Log.e("drawBitmap", ""+now1);
        Log.e("drawBitmap", ""+(now1-now));
        return bitmap;
    }

    /**
     * 绘制水印背景色
     */
    public Bitmap drawBackground(Bitmap bitmap) {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        Paint paint = new Paint();
        paint.setDither(true);
        paint.setFilterBitmap(true);
        paint.setColor(Color.BLACK);
        paint.setAlpha(100);
        canvas.drawBitmap(bitmap, 0, 0, null);
        RectF rectF = new RectF(20, newBitmap.getHeight() - backgroundHeight, newBitmap.getWidth()-20, newBitmap.getHeight()-20);
        canvas.drawRoundRect(rectF, 10, 10, paint);
        return newBitmap;
    }

    /**
     * 绘制水印文字
     */
    public Bitmap drawText(Context context, Bitmap bitmap, WatermarkEntity waterMaskBean) {
        Bitmap.Config bitmapConfig = bitmap.getConfig();
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }
        bitmap = bitmap.copy(bitmapConfig, true);

        Canvas canvas = new Canvas(bitmap);
        TextPaint paintSmall = getPaint(smallFontSize);
        TextPaint paintBig = getPaint(bigFontSize);

        offsetRightImageX = bitmap.getWidth()/2;
        offsetRightTextX = offsetRightImageX + 50;
        picHeight = bitmap.getHeight();
        picWidth = bitmap.getWidth();

        canvas.drawText("2022-02-02", offsetLeftX, picHeight - sumHeight, paintSmall);
        canvas.drawText("10:10", offsetLeftX - 10, picHeight - (sumHeight - lineHeight * 1 - 50), paintBig);

        if (waterMaskBean != null){
            Bitmap titleBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_water_mask_title);
            Bitmap memberBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_water_mask_member);
            Bitmap cooperationBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_water_mask_cooperate);
            Bitmap customerBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_water_mask_client);
            Bitmap logoBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_water_mask_logo);

            float titleHeight = picHeight - (sumHeight - lineHeight * 0);
            float memberHeight = picHeight - (sumHeight - lineHeight * 1);
            float cooperationHeight = picHeight - (sumHeight - lineHeight * 2);
            float customerHeight = picHeight - (sumHeight - lineHeight * 3);
            float addressHeight = picHeight - (sumHeight - lineHeight * 4);
            logoRightOffset = picWidth - 35;//padding：40
            logoBottomOffset = picHeight - 35;//右下角

            //Rect:int left, int top, int right, int bottom;上下左右的四点；宽=right-left；高=bottom-top
            Rect titleRect = new Rect((int) offsetRightImageX, (int)(titleHeight-offsetRightY), (int)offsetRightImageX + imageSize, (int)(titleHeight-offsetRightY) + imageSize);
            Rect memberRect = new Rect((int) offsetRightImageX, (int)(memberHeight-offsetRightY), (int)offsetRightImageX + imageSize, (int)(memberHeight-offsetRightY) + imageSize);
            Rect cooperationRect = new Rect((int) offsetRightImageX, (int)(cooperationHeight-offsetRightY), (int)offsetRightImageX + imageSize, (int)(cooperationHeight-offsetRightY) + imageSize);
            Rect customerRect = new Rect((int) offsetRightImageX, (int)(customerHeight-offsetRightY), (int)offsetRightImageX + imageSize, (int)(customerHeight-offsetRightY) + imageSize);
            Rect logoRect = new Rect((int) (logoRightOffset - logoWidth), (int)(logoBottomOffset - logoHeight), (int)logoRightOffset, (int)logoBottomOffset);//logo右下角

            if (!TextUtils.isEmpty(waterMaskBean.getTitle())){
                canvas.drawBitmap(titleBitmap, null, titleRect, null);
                canvas.drawText(waterMaskBean.getTitle(), offsetRightTextX, titleHeight, paintSmall);
            }
            if (!TextUtils.isEmpty(waterMaskBean.getMember())){
                canvas.drawBitmap(memberBitmap, null, memberRect, null);
                canvas.drawText(waterMaskBean.getMember(), offsetRightTextX, memberHeight, paintSmall);
            }

            if (!TextUtils.isEmpty(waterMaskBean.getCooperation())){
                canvas.drawBitmap(cooperationBitmap, null, cooperationRect, null);
                canvas.drawText(waterMaskBean.getCooperation(), offsetRightTextX, cooperationHeight, paintSmall);
            }

            if (!TextUtils.isEmpty(waterMaskBean.getClient())){
                canvas.drawBitmap(customerBitmap, null, customerRect, null);
                canvas.drawText(waterMaskBean.getClient(), offsetRightTextX, customerHeight, paintSmall);
            }

//            canvas.drawBitmap(logoBitmap, null, logoRect, null);

            if (!TextUtils.isEmpty(waterMaskBean.getAddress())){
                canvas.drawText(waterMaskBean.getAddress(), offsetLeftX, addressHeight, paintSmall);
            }
        }
        return bitmap;
    }

    /**
     * 获取画布Paint
     */
    public TextPaint getPaint(float textSize){
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        paint.setDither(true);
        paint.setAntiAlias(true);
        paint.setFilterBitmap(false);
        paint.setTextSize(textSize);
        return paint;
    }

    /**
     * 保存水印图片文件
     */
    public String saveWaterMask(Context context, Bitmap bitmap) {
        long now = System.currentTimeMillis();
        Log.e("saveWaterMask", ""+now);
        if (bitmap == null){
            return null;
        }
        File dir = new File(DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String waterMaskFileName = DIR + System.currentTimeMillis() + "."+ Bitmap.CompressFormat.JPEG.name();
        File file = new File(waterMaskFileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)) {
                bitmap.recycle();
                out.flush();
                out.close();
            }
            //保存图片要刷新数据库：不然在相册不显示
//            Uri uri = Uri.fromFile(file);
//            if (context != null) context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (Exception e) {
            e.printStackTrace();
        }
        long now1 = System.currentTimeMillis();
        Log.e("saveWaterMask", ""+now1);
        Log.e("saveWaterMask", ""+(now1-now));
        return waterMaskFileName;
    }




}
